import {createRouter, createWebHistory} from 'vue-router'
import {getToken, getUserInfo, loadUserInfo} from '@/utils/auth'


//默认导入静态路由
import static_router from './static_router'
import HomeView from "@/views/HomeView.vue";

// console.log('====静态 static_router', static_router)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: static_router
})


const whitelist = ['/login']
// 全局路由守卫  当未登录并且访问的不是白名单的路径，需要切换到  login
router.beforeEach((to, from, next) => {
  const path = to.path;
  const token = getToken()
  if (whitelist.indexOf(path) != -1) {
    // console.log("已经登录");
    next()
  } else if (token) {
    if (getUserInfo()) {
      next()
    } else {
      //如果没有身份信息则 重新加载后 再跳转
      loadUserInfo((permissions) => {
        // console.log("JSON.stringify(permissions)：", JSON.stringify(permissions))
        // 已经加载用户信息
        // console.log("====切换路由前无用户身份信息，权限信息，加载用户信息===")

        //构造动态路由
        router.addRoute(buildDynamic(permissions));

        // router.getRoutes().forEach(route=>{
        //     console.log("====动态路由====",route)
        // })
        //由于是动态路由，如果不加to的话  在进入beforeEach 方法之前已经完成匹配结果是没有的，会导致页面空白
        next({...to, replace: true})
      })
    }

  } else {
    // console.log("未登录");
    next("/login")
  }

})

/**
 * 通过路径获取组件，如果获取不到就跳转到404
 * @param componentPath
 * @returns {{(): Promise<string extends keyof KnownAsTypeMap ? KnownAsTypeMap[string] : unknown>, (): Promise<string extends keyof KnownAsTypeMap ? KnownAsTypeMap[string] : unknown>}}
 */
function existsView(componentPath) {
  //glob
  const modules = import.meta.glob('../views/**/*.vue');
  return modules[componentPath] ? true : false;
}

/**
 * 通过菜单权限构造动态路由
 * @param permissions
 * @returns {{path: string, component: {}, children: *[], name: string}}
 */
function buildDynamic(permissions) {
  let dynamicRoutes = [];

  //一级菜单是文件夹
  permissions.forEach(menu => {
    if (menu.children) {
      //二级菜单 路由 menu.children
      menu.children.forEach(({path, component, menuName}) => {
        console.log("path:"+path)
        dynamicRoutes.push({
          path: '/' + path,
          name: path,
          // component: () => import('../views/permission/role/index.vue'),
          component: () => {
            const exists = existsView('../views/' + component + '.vue')

            if (exists) {
              return import(/* @vite-ignore */ '../views/' + component + '.vue')
            } else {
              console.log('../views/' + component + '.vue :::::    不存在 ')
              return import('../views/404.vue')
            }
          },
        })
      })
    }
  })

  console.log("==动态路由， children ; dynamicRoutes", dynamicRoutes)

  //构造好的
  const allRoutes = {
    path: '/',
    name: 'home',
    component: HomeView,
    children: dynamicRoutes
  }

  // console.log("组装好的 路由表: ",allRoutes)
  return allRoutes;

}

export default router




